package com.school.chapter01.SingleLinkedList;

import com.school.chapter01.DoubleLinkedList_.DuLinkList;

public class LinkedList_<E> {
    // Node
    private class Node {
        //
        private E e;
        //
        private Node next;

        public Node() {
            this(null,null);
        }

        public Node(E e) {
            this(e, null);
        }
        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public E getE() {
            return e;
        }

        public void setE(E e) {
            this.e = e;
        }
    }
    //链表长度
    private int size;
    //链表头节点
    private Node dummyHead;
    public LinkedList_() {
        this.size = 0;
        dummyHead = new Node();
    }
    public boolean insert(E e ,int i){
        if (i < 0 || i > size) {
            throw new IndexOutOfBoundsException("索引越界");
        }

            if (i == 0){
                dummyHead = new Node(e);
            }
            else{
                Node prev = dummyHead;
                for (int j = 0; j < i - 1; j++) {
                    prev = prev.next;
                }
                prev.next = new Node(e,prev.next);
            }

        size++;
        return true;
    }
    public Node deleteByIndex(int index){
        Node node = new Node();
        for (int i = 0; i < index - 1; i++) {
            node = node.next;
        }
        Node del = node.next;
        node.next = del.next;
        size--;
        return del;
    }
    public void add(E e){
        if (0 == size){
            insert(e,0);
        }else
        insert(e,size);
    }
    public String toString() {
//链表为空链表

            StringBuilder sb = new StringBuilder("[");
            for (Node current = dummyHead; current != null; current = current.next) {
                sb.append(current.e + ", ");
            }
            int len = sb.length();
            return sb.delete(len - 2, len).append("]").toString();
        }

}